package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;

    @ApiOperation("创建站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("短信内容") @RequestParam("content") @NonNull String content){
        //用户当前状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("当前用户已被禁言!禁止发送短信! userId:{}",user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //不能给自己发送信息
        if(user.getId().equals(receiveUserId)){
            log.warn("发送失败!无法向自己发送站内信");
            return AppResult.failed(ResultCode.CAN_NOT_SEND_TO_YOURSELF);
        }

        //校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(null==receiveUser || receiveUser.getDeleteState()==1){
            log.warn("发送失败!接收用户不存在!");
            return AppResult.failed(ResultCode.RECEIVER_NOT_EXIST);
        }

        //封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUser.getId());
        message.setContent(content);

        //调用service
        messageService.create(message);
        //成功
        log.info("站内信发送成功!");
        return AppResult.success("发送成功!");
    }


    @ApiOperation("获取未读站内信数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }


    @ApiOperation("获取站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        List<Message> messageList = messageService.selectByReceiveUserId(user.getId());
        log.info("获取站内信列表成功!");
        return AppResult.success(messageList);
    }


    @ApiOperation("更新站内信状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //查询站内信
        Message message = messageService.selectById(id);
        if(null == message  || message.getDeleteState()==1){
            log.warn("短信不存在");
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXIST);
        }

        //该站内信是否是自己的
        if(!user.getId().equals(message.getReceiveUserId())){
            log.warn("站内信不是该用户的!");
            return AppResult.failed(ResultCode.MESSAGE_NOT_YOURSELF);
        }
        messageService.updateStateById(id,(byte) 1);

        log.info("阅读站内信成功!");
        return AppResult.success();
    }


    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("要回复的正文") @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("当前用户已被禁言! userId:{}",user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //不能给自己回复
        if(user.getId().equals(repliedId)){
            log.warn("禁止用户向自己发送信息!");
            return AppResult.failed(ResultCode.CAN_NOT_SEND_TO_YOURSELF) ;
        }

        //校验站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if(null == existsMessage || existsMessage.getDeleteState()==1){
            log.warn("站内信不存在! repliedId:{}",repliedId);
            return AppResult.failed(ResultCode.MESSAGE_NOT_EXIST) ;
        }

        //构造
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);

        messageService.reply(repliedId,message);

        log.info("回复站内信成功!");
        return AppResult.success();
    }
}
